package com.chukun.flink.stream.action.fraud.rules.functions;

import com.chukun.flink.stream.action.fraud.rules.utils.RuleParser;
import com.chukun.flink.stream.action.fraud.rules.model.Rule;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.util.Collector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author chukun
 * @version 1.0.0
 * @description 规则解码器
 * @createTime 2022年05月22日 15:09:00
 */
public class RuleDeserializer extends RichFlatMapFunction<String, Rule> {

    private static final Logger logger = LoggerFactory.getLogger(RuleDeserializer.class);

    private transient RuleParser ruleParser;

    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);
        ruleParser = new RuleParser();
    }

    @Override
    public void flatMap(String ruleMsg, Collector<Rule> collector) throws Exception {
        try {
            Rule rule = ruleParser.fromString(ruleMsg);
            if (rule.getRuleState() != Rule.RuleState.CONTROL && rule.getRuleId() == null) {
                throw new NullPointerException("ruleId cannot be null: " + rule);
            }
            collector.collect(rule);
        } catch (Exception e) {
            logger.warn("Failed parsing rule {}, dropping it: ", ruleMsg, e);
        }
    }
}
